package xiaoa.java.netty;



import java.nio.charset.Charset;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import io.netty.buffer.Unpooled;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.http.multipart.DefaultHttpDataFactory;
import io.netty.handler.codec.http.multipart.HttpPostRequestEncoder;
import io.netty.handler.codec.http.multipart.HttpPostRequestEncoder.EncoderMode;

import org.apache.log4j.Logger;

/**
 * http连接工具类
 * @author xiaoa
 * @date 2017年7月25日 下午1:54:24
 * @version V1.0
 *
 */
public class HttpClientUtils {
	
	/**
	 * 管理工具
	 */
	private static HttpClient  client = null;
	
	public static void init(){
		client = new PoolHttpClient(10, 10 * 1000,  0x7FFFF, 20 , 10 * 1000);
//         client = new SimpleHttpClient();
	}
	
	public static void init(HttpClient client){
		HttpClientUtils.client = client;
	}

	/**
	 * 发送post请求
	 * @Title: doPost
	 * @param url
	 * @param parmaMap
	 * @return
	 * @throws Exception
	 * @author xiaoa
	 */
	public static HttpResponseResult doPost(String url , Map<String, String>  parmaMap,  Map<String, String>  handerMap, Charset charset) throws Exception{

		HttpRequest  request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, url);

		if (parmaMap != null && parmaMap.size() > 0){
			
			// 创建post提交表单
			HttpPostRequestEncoder  requestPost = new HttpPostRequestEncoder(new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE), request, false,
					charset, EncoderMode.RFC1738);

			if (parmaMap != null && parmaMap.size() > 0){

				for (String key : parmaMap.keySet()){
					requestPost.addBodyAttribute(key, parmaMap.get(key));
				}
			}

			return client.doRequest(requestPost.finalizeRequest() ,  handerMap);
		}

		return client.doRequest(request , handerMap );
	}
	
	
	/**
	 * 提交
	 * @Title: doPost
	 * @param url
	 * @param parmaMap
	 * @param handerMap
	 * @param charset
	 * @return
	 * @throws Exception
	 * @author xiaoa
	 */
	public static HttpResponseResult doPutData(String url , byte[] data, HttpMethod method  ,  String contentType ,  Map<String, String>  handerMap,  Charset charset) throws Exception{
	
		DefaultFullHttpRequest  request = null;
		if (data != null && data.length > 0 ){
			request  = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, method, url, Unpooled.wrappedBuffer(data));
			request.headers().add(HttpHeaderNames.CONTENT_LENGTH, request.content().readableBytes());
		}else {
			request  = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, method, url);
		}
		
		if (handerMap == null){
			handerMap = new HashMap<>();
		}
		
		if (contentType != null && contentType.trim().length() > 0){
			handerMap.put("Content-Type", contentType + " " + charset.toString());
		}else{
			handerMap.put("Content-Type", "application/json; " + charset.toString());
			handerMap.put("Accept", "application/json, text/javascript, */*; q=0.01");
		}
		
		return client.doRequest(request , handerMap );
	}


	/**
	 * 发送get请求
	 * @param url
	 * @param parmaMap
	 * @return
	 * @throws Exception
     */
	public static HttpResponseResult doGet(String url , Map<String, String>  parmaMap ,  Map<String, String>  handerMap , Charset charset ) throws Exception{

		String query = null;

		QueryStringEncoder requestGet = new QueryStringEncoder(url  ,charset);

		if (parmaMap != null && parmaMap.size() > 0){

			for (String key : parmaMap.keySet()){
				requestGet.addParam(key , parmaMap.get(key));
			}
		}

		query = requestGet.toString();
		
		DefaultFullHttpRequest  request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, query );
		
		return client.doRequest(request , handerMap);
		
	}

	public static void main(String[] args)throws Exception {


//		// 设置加载
//		// 设置密匙存储库
//		System.setProperty("javax.net.ssl.keyStore", "E:\\Users\\Administrator\\git\\java1.7Dome\\resources\\cert\\sslclientkeys");
//		System.setProperty("javax.net.ssl.keyStorePassword", "123456");
//
//		// 设置信任密匙库
//		System.setProperty("javax.net.ssl.trustStore", "E:\\Users\\Administrator\\git\\java1.7Dome\\resources\\cert\\sllclienttrust");
//		System.setProperty("javax.net.ssl.trustStorePassword", "123456");

		init();
		
		Log.setDebug(false);
		
		Logger.getLogger(HttpClientUtils.class);
		
		Runnable exceRun = new Runnable() {
			
			@Override
			public void run() {
				while(true){
//					
				try {
				
				final LinkedHashMap<String, String>  parmas = new LinkedHashMap<>();
		
				parmas.put("wd", "shanghai");
				parmas.put("message" , "北京");
				parmas.put("time" , System.currentTimeMillis() + "");
		
				parmas.put("ie", "UTF-8");
		
				final Map<String, String>  handerMap = new HashMap<>();
				handerMap.put("http.socket.timeout", 7 * 1000 +"");
			
				
				HttpResponseResult  result = null;
				
				
				try {
					result =  doPost("http://xiaoa0/SpringDome/activemq/testSync", parmas , handerMap , Charset.forName("utf-8"));
				} catch (Exception e) {
					result =  doPost("http://xiaoa0/SpringDome/activemq/testSync", parmas , handerMap , Charset.forName("utf-8"));
				}
				

				String resustr = result.getBodyToString();

				System.out.println(" resustr size = " + resustr.length());
				
				} catch (Throwable e) {
					
                    System.out.println("异常");
					e.printStackTrace();
//					System.exit(121);
				}

				}
			}
		};
	
		for (int i = 0; i < 100 ; i ++ ){
			
			new Thread(exceRun).start();

		}
		

//		parmas.put("wd", "北京");
////	
//		try {
//			HttpResponseResult  result2 = doGet("https://www.baidu.com/s", parmas , handerMap,Charset.forName("utf-8"));
//			
//			for (String key : result2.handles.keySet()){
//				
//				System.out.println( key + ":" +  result2.handles.get(key) );
//			}
//	
//			FileUtils.writeStringToFile(new File("e:/html2.html"), result2.getBodyToString() , "utf-8");
//
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		System.out.println("成功 北京");

	}
	
	
	
	

}
